﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GolfLeague.EditModels;
using GolfLeague.Models;
using GolfLeague.ViewModels;

namespace GolfLeague.Controllers
{
    public class MatchController : Controller
    {
        MatchInterface matchInterface = new MatchInterface();
        RoundInterface roundInterface = new RoundInterface();
        TeamInterface teamInterface = new TeamInterface();

        //
        // GET: /Match/5

        [Authorize(Roles = "Administrator")]
        public ActionResult Index(int id)
        {
            List<Team> TeamList = new List<Team>();
            List<StandardDropdown> TeamDropdown = new List<StandardDropdown>();
            List<int> TeamIDList = new List<int>();
            teamInterface.GetAllActiveTeams().OrderBy(t => t.TeamID).ToList().ForEach(delegate(Team team) { TeamIDList.Add(team.TeamID); });
            IEnumerable<Match> Matches = matchInterface.GetRoundMatches(id);

            foreach (Match match in Matches)
                foreach (TeamMatch teamMatch in matchInterface.GetMatchTeamMatches(match.MatchID))
                    TeamIDList.Remove(teamMatch.TeamID);

            TeamIDList.ForEach(delegate(int teamID)
            { 
                Team team = teamInterface.GetTeam(teamID);
                TeamList.Add(team);
                IEnumerable<Player> teamPlayers = teamInterface.GetTeamPlayers(teamID);
                TeamDropdown.Add(new StandardDropdown
                {
                    dropdownID = teamID,
                    dropdownText = string.Format("{0} ({1}/{2})", team.TeamName, teamPlayers.First().LastName, teamPlayers.Last().LastName)
                });
            });

            Round round = roundInterface.GetRound(id);
            DateTime matchDate;
            if (Matches.Count() > 0)
                matchDate = Matches.Last().MatchTime;
            else
            {
                matchDate = round.RoundDate;
                if (matchDate.Hour == 0) matchDate = matchDate.AddHours(DateTime.Now.Hour);
                if (matchDate.Minute == 0) matchDate = matchDate.AddMinutes(DateTime.Now.Minute);
            }
            return View(new MatchEditModel
            {
                Matches = Matches,
                MatchesView = matchInterface.GetMatchViewModels(id),
                NewMatch = new Match { RoundID = id, MatchTime = matchDate },
                MatchTime = matchDate.ToShortTimeString(),
                Round = round,
                Teams = TeamList,
                TeamDropdown = TeamDropdown
            });
        }

        //
        // POST: /Match/5
        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Index(MatchEditModel matchEditModel)
        {
            if (ModelState.IsValid)
            {
                DateTime newTime;
                DateTime.TryParse(matchEditModel.MatchTime, out newTime);
                matchEditModel.NewMatch.MatchTime = matchEditModel.NewMatch.MatchTime.Date + newTime.TimeOfDay;
                matchInterface.AddMatch(matchEditModel.NewMatch);
                matchInterface.Save();

                TeamMatch teamA = new TeamMatch
                {
                    TeamID = matchEditModel.TeamA,
                    MatchID = matchEditModel.NewMatch.MatchID
                };

                TeamMatch teamB = new TeamMatch
                {
                    TeamID = matchEditModel.TeamB,
                    MatchID = matchEditModel.NewMatch.MatchID
                };

                matchInterface.AddTeamMatch(teamA);
                matchInterface.AddTeamMatch(teamB);
                matchInterface.Save();

                return RedirectToAction("Index");
            }
            else
            {
                return View(matchEditModel);
            }
        }

        //
        // GET: /Match/MatchEdit/5

        [Authorize(Roles = "Administrator")]
        public ActionResult MatchEdit(int id)
        {
            List<StandardDropdown> TeamDropdown = new List<StandardDropdown>();
            Match match = matchInterface.GetMatch(id);

            foreach (Team team in teamInterface.GetAllActiveTeams())
            {
                IEnumerable<Player> teamPlayers = teamInterface.GetTeamPlayers(team.TeamID);
                TeamDropdown.Add(new StandardDropdown
                {
                    dropdownID = team.TeamID,
                    dropdownText = string.Format("{0} ({1}/{2})", team.TeamName, teamPlayers.First().LastName, teamPlayers.Last().LastName)
                });
            }

            
            IEnumerable<Match> matches = matchInterface.GetRoundMatches(match.RoundID);
            IEnumerable<Team> teams = matchInterface.GetMatchTeams(match.MatchID);

            return View("Index", new MatchEditModel
            {
                Matches = matches,
                TeamA = teams.First().TeamID,
                TeamB = teams.Last().TeamID,
                MatchesView = matchInterface.GetMatchViewModels(match.RoundID),
                Round = roundInterface.GetRound(match.RoundID),
                NewMatch = match,
                MatchTime = match.MatchTime.ToShortTimeString(),
                Teams = teamInterface.GetAllActiveTeams(),
                TeamDropdown = TeamDropdown
            });
        }

        //
        // POST: /Match/MatchEdit/5
        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult MatchEdit(MatchEditModel matchEditModel)
        {
            Match updateMatch = matchInterface.GetMatch(matchEditModel.NewMatch.MatchID);
            DateTime newTime;
            DateTime.TryParse(matchEditModel.MatchTime, out newTime);
            updateMatch.MatchTime = newTime;
            //updateMatch.TeamA = matchEditModel.NewMatch.TeamA;
            //updateMatch.TeamB = matchEditModel.NewMatch.TeamB;

            if (TryUpdateModel(updateMatch))
            {
                matchInterface.Save();
                return RedirectToAction("Index", new { id = updateMatch.RoundID });
            }
            else
            {
                matchEditModel.Matches = matchInterface.GetRoundMatches(updateMatch.RoundID);
                matchEditModel.Teams = teamInterface.GetAllActiveTeams();
                List<StandardDropdown> TeamDropdown = new List<StandardDropdown>();
                foreach (Team team in teamInterface.GetAllActiveTeams())
                {
                    IEnumerable<Player> teamPlayers = teamInterface.GetTeamPlayers(team.TeamID);
                    TeamDropdown.Add(new StandardDropdown
                    {
                        dropdownID = team.TeamID,
                        dropdownText = string.Format("{0} ({1}/{2})", team.TeamName, teamPlayers.First().LastName, teamPlayers.Last().LastName)
                    });
                }
                matchEditModel.TeamDropdown = TeamDropdown;
                matchEditModel.NewMatch = updateMatch;
                return View("Index", matchEditModel);
            }
        }

        //
        // POST: /Match/MatchDelete/5
        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult MatchDelete(int matchID)
        {
            Match deleteMatch = matchInterface.GetMatch(matchID);
            deleteMatch.PlayerMatches.ToList().ForEach(delegate(PlayerMatch playerMatch) { matchInterface.DeletePlayerMatch(playerMatch); });
            deleteMatch.TeamMatches.ToList().ForEach(delegate(TeamMatch teamMatch) { matchInterface.DeleteTeamMatch(teamMatch); });
            matchInterface.DeleteMatch(deleteMatch);
            matchInterface.Save();
            return RedirectToAction("Index", new { id = deleteMatch.RoundID });
        }
    }
}
